﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
///CustomGrid 的摘要说明
/// </summary>
namespace yncTechWeb.Controls
{
    public class PagnationGrid:Repeater
    {
        int pageSize = 20;
        int itemCount = 0;
        int currentPage = 1;
        int displayPages = 11;
        IList objectSource;
        DataTable tableSource;
        bool isObjectSource = false;
        bool pagination = true;
        string emptyText = "没有数据记录.";
        public event DataGridPageChangedEventHandler OnPageIndexChange;
        private static readonly Regex PageRegex = new Regex(string.Format(@"^&{0}=\d+",PageKey), RegexOptions.Compiled);

        const string AddLink = @"";

        const string PageKey = "page";

        /// <summary>
        /// 是事分页
        /// </summary>
        public bool IsPagination
        {
            get
            {
                return pagination;
            }
            set
            {
                pagination = value;
            }
        }

        /// <summary>
        /// 设置每个分页有多少条记录
        /// </summary>
        public int PageSize
        {
            get {
                return pageSize;
            }
            set
            {
                pageSize = value;
            }
        }
        /// <summary>
        /// 总共有多少页
        /// </summary>
        public int TotalPages
        {
            get
            {
                if (IsPagination)
                {
                    return ItemCount % PageSize == 0 ? ItemCount / PageSize : ItemCount / PageSize + 1;
                }
                return 1;
            }
        }

        /// <summary>
        /// 显示分布数量
        /// </summary>
        public int DisplayPages
        {
            get
            {
                return displayPages;
            }
            set
            {
                if (value % 2 == 0)
                {
                    displayPages = value + 1;
                }
                else
                {
                    displayPages = value;
                }
            }
        }

        /// <summary>
        /// 起始页为1
        /// </summary>
        public int CurrentPage
        {
            get
            {
                return currentPage;
            }
            set
            {
                currentPage = value;
            }
        }

        /// <summary>
        /// 数据为空时显示提示信息
        /// </summary>
        public string EmptyText
        {
            get
            {
                return emptyText;
            }
            set
            {
                emptyText = value;
            }
        }
        
        protected int ItemCount
        {
            get
            {
                return itemCount;
            }
            private set
            {
                itemCount = value;
            }
        }

        public override object DataSource
        {
            set
            {
                try
                {
                    objectSource = (IList)value;
                    ItemCount = objectSource.Count;
                    isObjectSource = true;
                    base.DataSource = objectSource;
                }
                catch
                {
                    isObjectSource = false;

                    if (value is DataTable)
                    {
                        tableSource = (DataTable)value;
                        ItemCount = tableSource.Rows.Count;
                    }
                    else
                    {
                        objectSource = null;
                        ItemCount = 0;
                    }
                    base.DataSource = tableSource;
                }
            }
            get
            {
                return  base.DataSource;
            }

        }

        public void SetPage(int index)
        {
            PageIndexChanged(new DataGridPageChangedEventArgs(null, index));
        }

        public void PageIndexChanged(DataGridPageChangedEventArgs e)
        {
            if (OnPageIndexChange != null)
            {
                OnPageIndexChange(this, e);
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            if (Visible)
            {
                string page = Context.Request.QueryString[PageKey];
                int outPage;
                if(!int.TryParse(page, out outPage) || outPage <= 0)
                {
                    outPage = 1;
                }
                CurrentPage = outPage;
                SetPage(outPage);
            }
        }

        protected override void OnDataBinding(EventArgs e)
        {

            if (pagination && ItemCount>0)//是否分页
            {
                if (CurrentPage > TotalPages)
                {
                    CurrentPage = TotalPages;
                }
                int start = (CurrentPage - 1) * PageSize;
                int end = start + Math.Min(PageSize, ItemCount - start);
                if (isObjectSource)
                {

                    IList listSource = new ArrayList(PageSize);
                    for (int i = start; i < end; i++)
                    {
                        listSource.Add(objectSource[i]);
                    }
                    base.DataSource = listSource;

                }
                else
                {
                    DataTable tableData = tableSource.Clone();
                    for (int i = start; i < end; i++)
                    {
                        tableData.ImportRow(tableSource.Rows[i]);
                    }
                    base.DataSource = tableData;

                }
            }
            base.OnDataBinding(e);
           
        }
        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write("<div style=\"padding-right:12px; display:block;\">");
            base.Render(writer);
            if (pagination && ItemCount>0)//是否分页
            {
                writer.Write(Pagnation());
            }
            writer.Write("</div>");
        }

        string Pagnation()
        {
            string retValue = "<div class=\"pager\" ><div class=\"total\">{0}</div><div class=\"pages\">{1}</div></div>";

            StringBuilder sbPages = new StringBuilder();
            string query = Context.Request.Url.Query.Replace("?", "&");
            query = PageRegex.Replace(query, string.Empty);
            StringBuilder pagesBuilder = new StringBuilder();
            Dictionary<int, string> pageDic = new Dictionary<int, string>();
            if (TotalPages > 1)
            {
                int pageStep = DisplayPages / 2;
                if (CurrentPage > 1)
                {
                    pagesBuilder.AppendFormat("<a href=\"?page=1{0}\">{1}</a>", query, yncSettings.Pagination.First);
                    pagesBuilder.AppendFormat("<a href=\"?page={0}{1}\">{2}</a>", CurrentPage - 1, query, yncSettings.Pagination.Previous);
                }
                else
                {
                    pagesBuilder.AppendFormat("<span class=\"disenable\">{0}</span>", yncSettings.Pagination.First);
                    pagesBuilder.AppendFormat("<span class=\"disenable\">{0}</span>", yncSettings.Pagination.Previous);
                }
                int i = 1;
                int maxPage = DisplayPages;
                //检查当前显示的页数是否小于总页数
                if (TotalPages <= DisplayPages)
                {
                    maxPage = TotalPages;
                }
                else
                {
                    if (currentPage > pageStep)
                    {
                        i = currentPage - pageStep;
                        maxPage = CurrentPage + pageStep;
                        if (maxPage > TotalPages)
                        {
                            maxPage = TotalPages;
                        }
                        if ((TotalPages - i) < DisplayPages)
                        {
                            i = TotalPages - DisplayPages;
                        }
                    }
                    else
                    {
                        maxPage = DisplayPages;
                    }
                }
                if (i > 1)
                {
                   pagesBuilder.Append("<span>...</span>");
                }
                for (; i <= maxPage; i++)
                {
                    if (i != CurrentPage)
                    {
                        pagesBuilder.AppendFormat("<a href=\"?page={0}{1}\"><span class=\"index\">{0}</span></a>", i, query);
                    }
                    else
                    {
                        pagesBuilder.AppendFormat("<span class=\"current\">{0}</span>", i);
                    }
                }
                if (maxPage != TotalPages)
                {
                    pagesBuilder.Append("<span>...</span>"); 
                }
                if (CurrentPage == TotalPages)
                {
                    pagesBuilder.AppendFormat("<span class=\"disenable\">{0}</span>", yncSettings.Pagination.Next);
                    pagesBuilder.AppendFormat("<span class=\"disenable\">{0}</span>", yncSettings.Pagination.Last);
                }
                else
                {
                    pagesBuilder.AppendFormat("<a href=\"?page={0}{1}\">{2}</a>", CurrentPage + 1, query, yncSettings.Pagination.Next);
                    pagesBuilder.AppendFormat("<a href=\"?page={0}{1}\">{2}</a>", TotalPages, query, yncSettings.Pagination.Last);
                }

            }
            return string.Format(retValue,string.Format(yncSettings.Pagination.TotalText,ItemCount,PageSize,currentPage,TotalPages),pagesBuilder.ToString());
        }
    }
}